<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      
      <!-- <el-form-item label="dtuId" prop="dtuId">
        <el-input
          v-model="queryParams.dtuId"
          placeholder="请输入dtuId"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="协议名称" prop="protocolType">
        <el-select v-model="queryParams.protocolType" placeholder="请选择协议" clearable style="width: 170px">
          <el-option v-for="dict in dict.type.protocol_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="协议名称" prop="protocolName">
        <el-input
          v-model="queryParams.protocolName"
          placeholder="请输入协议名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指令名称" prop="instructName">
        <el-input
          v-model="queryParams.instructName"
          placeholder="请输入指令名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item prop="dtuName" label="所属dtu：">
        <el-autocomplete @clear="dtuclear" clearable id="dtu" v-model="queryParams.dtuName" :fetch-suggestions="querySearchAsync" placeholder="请输入所属dtu" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
      </el-form-item>
      <el-form-item prop="plotId" label="小区名称：">
        <el-select v-model="queryParams.plotId" placeholder="请选择小区名称" clearable style="width: 170px"
          @change="xiaoquChange">
          <el-option v-for="dict in xiaoquData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="buildId" label="所属楼栋：">
        <el-select v-model="queryParams.buildId" placeholder="请选择楼栋" clearable style="width: 170px"
          @change="loudonChange">
          <el-option v-for="dict in loudongData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择单元：" prop="unitId">
        <el-select v-model="queryParams.unitId" placeholder="请选择单元">
          <el-option v-for="(item, index) in danyuanData" :key="index" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="门牌号" prop="houseNumber">
        <el-input
          v-model="queryParams.houseNumber"
          placeholder="请输入门牌号"
          clearable
          
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.instruct_send_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址域" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址域"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="handleAdd"
          v-hasPermi="['deviceInstruction:deviceInstruction:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deviceInstruction:deviceInstruction:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deviceInstruction:deviceInstruction:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="single"
          v-hasPermi="['deviceInstruction:deviceInstruction:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceInstructionList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="主键id" align="center" prop="id" /> -->
      <el-table-column label="所属dtu" align="center" prop="dtuName" />
      <el-table-column label="小区" align="center" prop="plotName" />
      <el-table-column label="楼栋" align="center" prop="buildName" />
      <el-table-column label="单元" align="center" prop="unitName" />
      <el-table-column label="门牌号" align="center" prop="houseNumber" />
      <!-- <el-table-column label="协议类型" align="center" prop="protocolName" /> -->
      <!-- 1：户用阀门协议 
2：单元阀门协议 
3：温室采集器协议    
4：户用热量表协议    
5：单元热量表协议  -->
      <el-table-column label="协议名称" align="center" prop="protocolName" />
      <!-- <el-table-column label="指令类型" align="center" prop="instructType" /> -->
      <el-table-column label="指令名称" align="center" prop="instructName" />
      
      <el-table-column label="地址域" align="center" prop="address" />
      <el-table-column label="指令集合(十六进制)" align="center" prop="instructionSet" show-overflow-tooltip />
      <el-table-column label="回复数据(十六进制)" align="center" prop="recoverMessage" show-overflow-tooltip />
      <!-- <el-table-column label="设备数据" align="center" prop="jsonData" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.instruct_send_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="设备回复数据" align="center" prop="jsonData" show-overflow-tooltip>
        
      </el-table-column>
      <el-table-column label="设备回复时间" align="center" prop="updateTime">
        
      </el-table-column>
      <el-table-column label="消息下发失败时间" align="center" prop="sendFailTime">
        
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deviceInstruction:deviceInstruction:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deviceInstruction:deviceInstruction:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改指令发送对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="dtuId" prop="dtuId">
          <el-input v-model="form.dtuId" placeholder="请输入dtuId" />
        </el-form-item>
        <el-form-item label="协议名称" prop="protocolName">
          <el-input v-model="form.protocolName" placeholder="请输入协议名称" />
        </el-form-item>
        <el-form-item label="指令名称" prop="instructName">
          <el-input v-model="form.instructName" placeholder="请输入指令名称" />
        </el-form-item>
        <el-form-item label="小区id" prop="plotId">
          <el-input v-model="form.plotId" placeholder="请输入小区id" />
        </el-form-item>
        <el-form-item label="楼栋id" prop="buildId">
          <el-input v-model="form.buildId" placeholder="请输入楼栋id" />
        </el-form-item>
        <el-form-item label="单元id" prop="unitId">
          <el-input v-model="form.unitId" placeholder="请输入单元id" />
        </el-form-item>
        <el-form-item label="住户id" prop="householdId">
          <el-input v-model="form.householdId" placeholder="请输入住户id" />
        </el-form-item>
        <el-form-item label="地址域" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址域" />
        </el-form-item>
        <el-form-item label="指令集合(十六进制)" prop="instructionSet">
          <el-input v-model="form.instructionSet" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.instruct_send_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceInstruction, getDeviceInstruction, delDeviceInstruction, addDeviceInstruction, updateDeviceInstruction } from "@/api/deviceInstruction/deviceInstruction";
import { getDtuUsrByName,listCPlotSelect, listBuildSelect, listBuildUnitSelect, listCustomModelSelect, listHouseholdClassifySelect, listEquipmentGroupSelect } from "@/api/system/utils"

export default {
  name: "DeviceInstruction",
  dicts: ['instruct_send_status',"protocol_type"],
  data() {
    return {
      //小区下拉
      xiaoquData:[],
      //楼栋下拉
      loudongData:[],
      //单元下拉
      danyuanData:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 指令发送表格数据
      deviceInstructionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dtuName:null,
        dtuId: null,
        protocolType: null,
        protocolName: null,
        instructType: null,
        instructName: null,
        plotId: null,
        buildId: null,
        unitId: null,
        houseNumber: null,
        address: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dtuId: [
          { required: true, message: "dtuId不能为空", trigger: "blur" }
        ],
        protocolType: [
// 1：户用阀门协议 
// 2：单元阀门协议 
// 3：温室采集器协议    
// 4：户用热量表协议    
// 5：单元热量表协议
           { required: true, message: "协议类型 不能为空", trigger: "change" }
        ],
        protocolName: [
          { required: true, message: "协议名称不能为空", trigger: "blur" }
        ],
        instructType: [
          { required: true, message: "指令类型不能为空", trigger: "change" }
        ],
        instructName: [
          { required: true, message: "指令名称不能为空", trigger: "blur" }
        ],
        plotId: [
          { required: true, message: "小区id不能为空", trigger: "blur" }
        ],
        buildId: [
          { required: true, message: "楼栋id不能为空", trigger: "blur" }
        ],
        unitId: [
          { required: true, message: "单元id不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址域不能为空", trigger: "blur" }
        ],
        instructionSet: [
          { required: true, message: "指令集合(十六进制)不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    //小区下拉
    listCPlotSelect({}).then(res => {
      this.xiaoquData = res.rows
      this.queryParams.plotId = res.rows[0].value
    }).then(res=>{
      listBuildSelect({ plotId: this.queryParams.plotId }).then(res => {
        this.loudongData = res.rows
      })
      this.getList();
    })
  },
  methods: {
    /** 查询指令发送列表 */
    getList() {
      this.loading = true;
      listDeviceInstruction(this.queryParams).then(response => {
        this.deviceInstructionList = response.rows;
        this.total = response.total;
        this.loading = false;
      },(err)=>{this.loading = false});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dtuId: null,
        protocolType: null,
        protocolName: null,
        instructType: null,
        instructName: null,
        plotId: null,
        buildId: null,
        unitId: null,
        householdId: null,
        address: null,
        instructionSet: null,
        jsonData: null,
        status: null,
        createBy: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      console.log("queryForm",this.queryForm);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加指令发送";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceInstruction(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改指令发送";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDeviceInstruction(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceInstruction(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除指令发送编号为"' + ids + '"的数据项？').then(function() {
        return delDeviceInstruction(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('deviceInstruction/deviceInstruction/exportDeviceInstruction', {
        ...this.queryParams
      }, `deviceInstruction_${new Date().getTime()}.xlsx`)
    },

    //选择小区时
    xiaoquChange(){
      this.loudongData = []
      this.danyuanData = []
      listBuildSelect({ plotId: this.queryParams.plotId }).then(res => {
        this.queryParams.buildId = null;
        this.queryParams.unitId = null;
        this.loudongData = res.rows
      })
    },
    //选择楼栋时
    loudonChange(){
      this.danyuanData = []
      listBuildUnitSelect({ buildId: this.queryParams.buildId }).then(res => {
        this.queryParams.unitId = null;
        this.danyuanData = res.rows
      });
    },
    //选择单元时



    // dtu选择事件
    querySearchAsync(queryString, cb) {
      getDtuUsrByName(queryString).then(({rows})=>{
        // console.log(res);
        let results = rows.map(item=>{
         return {
            'value':item.name,
            'id':item.id
          }
        })
        // var results = queryString ? rows.filter(this.createStateFilter(queryString)) : rows;
        cb(results)
      })
      },
      createStateFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
    handleSelect({value,id}) {
        console.log(value,id);
        this.queryParams.dtuName = value
        this.queryParams.dtuId = id
      },
      dtuclear(){
        this.queryParams.dtuName = null
        this.queryParams.dtuId = null
      }
  }
};
</script>
<style lang="scss" scoped>
#grid{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
}
</style>